package com.molichuxing.services.infrastructure.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.utils.Md5Util;
import com.molichuxing.services.infrastructure.bean.AioResultLogBean;
import com.molichuxing.services.infrastructure.dao.AioResultLogMapper;
import com.molichuxing.services.infrastructure.dto.request.modify.AioPayResultModifyDto;
import com.molichuxing.services.infrastructure.dto.response.PrepaymentDto;
import com.molichuxing.services.infrastructure.service.AiopayService;
import com.molichuxing.services.utils.PaymentUtil;

@Service("aiopayService")
public class AiopayServiceImpl implements AiopayService {
	private static final Logger logger = LoggerFactory.getLogger(AiopayServiceImpl.class);

	@Resource
	private AioResultLogMapper aioResultLogMapper;

	/**
	 * 生成大屏支付预支付单
	 * 
	 * @param payAmount
	 * @return
	 */
	@Override
	public PrepaymentDto orderPay(BigDecimal payAmount) {
		PrepaymentDto result = new PrepaymentDto();
		result.setOutTradeNo(PaymentUtil.getPayNumber() + "");
		Map<String, String> repData = new HashMap<>();
		repData.put("payNumber", result.getOutTradeNo());
		repData.put("payAmount", payAmount + "");
		repData.put("sign", Md5Util.md5Hex(JSONObject.toJSONString(repData)));
		result.setRequestData(JSONObject.toJSONString(repData));
		return result;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public boolean payResult(AioPayResultModifyDto modifyDto) {
		// 验证
		Map<String, String> param = new HashMap<>();
		param.put("payNumber", modifyDto.getPayNumber());
		param.put("payAmount", modifyDto.getPayAmount() + "");
		String sign = Md5Util.md5Hex(JSONObject.toJSONString(param));
		if (!sign.equals(modifyDto.getSign())) {
			logger.error("智能终端支付结果签名验证失败：{}", JSONObject.toJSONString(modifyDto));
			return false;
		}
		// 保存
		saveResultLog(modifyDto);
		if (!modifyDto.getIsSuccess()) {
			return true;
		}
		// TODO 判断支付类型

		return true;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public void saveResultLog(AioPayResultModifyDto modifyDto) {
		// 保存
		AioResultLogBean bean = new AioResultLogBean();
		bean.setPaymentId(modifyDto.getPaymentId());
		bean.setPayNumber(modifyDto.getPayNumber());
		bean.setResultData(modifyDto.getPayResultJson());
		aioResultLogMapper.create(bean);
	}

}
